package com.shu.thread;

public class ProductFactory {
	private int product = 0;

	public synchronized void produce() {
		if (this.product > 100) {
			try {
				System.out.println("产品已满,请稍候再生产");
				this.wait();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		} else {
			product++;
			System.out.println("生产者生产第" + this.product + "个产品.");
			notifyAll(); // 通知等待区的消费者可以取出产品了
		}
	}

	public synchronized void consume() {
		if (this.product <= 0) {
			try {
				System.out.println("缺货,稍候再取");
				this.wait();
			} catch (Exception e) {
				e.printStackTrace();
			}
			return;
		} else {
			System.out.println("消费者取走了第" + this.product + "个产品.");
			this.product--;
			notifyAll(); // 通知等待去的生产者可以生产产品了
		}
	}

	public static void main(String[] args) {
		ProductFactory pf = new ProductFactory();
		for(;;) {
			pf.consume();
		}
	}

}
